import React, { useEffect } from 'react';

import { ProCard } from '@ant-design/pro-components';
import 'highlight.js/styles/github-dark.css';
import 'github-markdown-css/github-markdown.css';
import './index.scss';
import Markdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight'

interface Props {
  content: string;
  className?: string;
}

const parseText = (text: string) => {
  const result: any = {};
  const lines = text.split('\n');

  let isInMetadata = false;
  let currentKey = '';

  for (const line of lines) {
    // 开始或结束 metadata 区域
    if (line.trim() === '---') {
      isInMetadata = !isInMetadata;
      continue;
    }
    // 解析 metadata 区域内的 key 和 value
    if (isInMetadata) {
      const [key, value] = line.split(':').map(part => part.trim());
      if (key && value) {
        result[key] = value;
        currentKey = key;
      } else if (currentKey) {
        // 如果当前行没有冒号分割，则将其内容添加到上一个 key 的值
        result[currentKey] += '\n' + line.trim();
      }
    }
  }
  return result;
}

const replaceMetadataWithHeading = (text: string, newText: string) => {
  const lines = text.split('\n');
  let isInMetadata = false;
  let result = '';

  for (const line of lines) {
    if (line.trim() === '---') {
      isInMetadata = !isInMetadata;
      result += isInMetadata ? `# ${newText}` : ''; // 如果在 metadata 区域内，则添加一级标题
      continue;
    }
    result += isInMetadata ? '' : line + '\n'; // 如果在 metadata 区域内，则跳过原文本
  }
  return result.trim(); // 移除多余的空格
}

const MarkDown: React.FC<Props> = ({ content, className }) => {
  const handleData = (str: string) => {
    const meta = parseText(str)
    return replaceMetadataWithHeading(str, meta?.title)
  }

  return <>
    <ProCard>
      <div className="markdown-body">
        <Markdown rehypePlugins={[rehypeHighlight]}>{handleData(content)}</Markdown>
      </div>
    </ProCard>
  </>;
};

export default MarkDown;
